import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from '../../services/api';
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '../../utils/jwtUtils';

// 异步登录操作
export const loginUser = createAsyncThunk(
  'user/loginUser',
  async ({ phone, password }, { rejectWithValue }) => {
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 调用真实API进行登录
      const response = await axios.post('/auth/login', { phone, password });
      if (response.data.token) {
        setToken(response.data.token);
        setUserInfo(response.data.user);
      }
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '登录失败');
    }
  }
);

// 异步获取验证码操作
export const getVerificationCode = createAsyncThunk(
  'user/getVerificationCode',
  async (phone, { rejectWithValue }) => {
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 调用真实API发送验证码
      const response = await axios.post('/auth/send-code', { phone });
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '获取验证码失败');
    }
  }
);

// 异步验证码登录操作
export const loginWithVerificationCode = createAsyncThunk(
  'user/loginWithVerificationCode',
  async ({ phone, code }, { rejectWithValue }) => {
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 调用真实API进行验证码登录
      const response = await axios.post('/auth/login/code', { phone, code });
      if (response.data.token) {
        setToken(response.data.token);
        setUserInfo(response.data.user);
      }
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '登录失败');
    }
  }
);

// 异步注册操作
export const registerUser = createAsyncThunk(
  'user/registerUser',
  async ({ phone, password }, { rejectWithValue }) => {
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 调用真实API进行注册
      const response = await axios.post('/auth/register', { phone, password });
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || '注册失败');
    }
  }
);

// 退出登录操作
export const logoutUser = createAsyncThunk(
  'user/logoutUser',
  async (_, { rejectWithValue }) => {
    try {
      // 直接清除本地存储的token和用户信息，避免触发token刷新
      removeToken();
      removeUserInfo();
      
      // 尝试发送退出登录请求（失败也不影响主流程）
      try {
        await axios.post('/auth/logout');
      } catch (apiError) {
        console.log('退出登录请求失败，但已清除本地认证信息:', apiError);
      }
      
      return {};
    } catch (error) {
      return rejectWithValue('退出登录处理失败');
    }
  }
);

// 初始化用户状态
const initialState = {
  userInfo: getUserInfo() || null,
  token: getToken() || null,
  isLoading: false,
  error: null,
  isAuthenticated: !!getToken(),
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    setUserFromStorage: (state) => {
      state.userInfo = getUserInfo() || null;
      state.token = getToken() || null;
      state.isAuthenticated = !!getToken();
    },
  },
  extraReducers: (builder) => {
    builder
      // 登录操作
      .addCase(loginUser.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.isLoading = false;
        state.userInfo = action.payload.user;
        state.token = action.payload.token;
        state.isAuthenticated = true;
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 获取验证码操作
      .addCase(getVerificationCode.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(getVerificationCode.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(getVerificationCode.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 验证码登录操作
      .addCase(loginWithVerificationCode.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loginWithVerificationCode.fulfilled, (state, action) => {
        state.isLoading = false;
        state.userInfo = action.payload.user;
        state.token = action.payload.token;
        state.isAuthenticated = true;
      })
      .addCase(loginWithVerificationCode.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 退出登录操作
      .addCase(logoutUser.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(logoutUser.fulfilled, (state) => {
        state.isLoading = false;
        state.userInfo = null;
        state.token = null;
        state.isAuthenticated = false;
      })
      .addCase(logoutUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 注册操作
      .addCase(registerUser.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(registerUser.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(registerUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      });
  },
});

export const { clearError, setUserFromStorage } = userSlice.actions;

export default userSlice.reducer;